﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WhereAmIConnected
{
    public partial class FormMain : Form
    {
        private bool checkIsDone = false;
        private string connError = "";

        public FormMain()
        {
            InitializeComponent();

            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.WorkerReportsProgress = true;

            // Retrieve the saved ConnString
            this.textBoxConnectionString.Text = Properties.Settings.Default.ConnString;
        }

        private void buttonTest_Click(object sender, EventArgs e)
        {
            /*
            Server=tcp:AGListener,1433;Database=AdventureWorks;IntegratedSecurity=SSPI;MultiSubnetFailover=Yes;ApplicationIntent=ReadOnly
            */
            this.toolStripProgressBarConnecting.Visible = true;
            this.labelServer.Visible = false;
            this.labelServer.Text = "< ! ERROR ! >";
            this.labelIamConn.Visible = false;
            this.textBoxConnectionString.Enabled = false;
            this.buttonTest.Enabled = false;
            this.checkIsDone = false;
            this.connError = "";

            StartBackgroundWork();
        }

        private void testConnection()
        {
            if (!this.checkIsDone) { 
                string connectionString = this.textBoxConnectionString.Text;

                // Provide the query string with a parameter placeholder.
                string queryString = "SELECT @@servername";

                using (SqlConnection connection =
                    new SqlConnection(connectionString))
                {
                    // Create the Command and Parameter objects.
                    SqlCommand command = new SqlCommand(queryString, connection);

                    try
                    {
                        connection.Open();
                        SqlDataReader reader = command.ExecuteReader();
                        reader.Read();

                        this.Invoke(new Action(() => { this.labelServer.Text = reader[0].ToString(); }));
                        
                        reader.Close();

                        this.checkIsDone = true;
                    }
                    catch (Exception ex)
                    {
                        this.connError = ex.Message;
                        this.checkIsDone = false;
                    }
                   
              
                }
            }
            
        }

        private void StartBackgroundWork()
        {
            if (Application.RenderWithVisualStyles)
                toolStripProgressBarConnecting.Style = ProgressBarStyle.Marquee;
            else
            {
                toolStripProgressBarConnecting.Style = ProgressBarStyle.Continuous;
                toolStripProgressBarConnecting.Maximum = 100;
                toolStripProgressBarConnecting.Value = 0;
                timer.Enabled = true;
            }

            if (backgroundWorker.IsBusy != true)
            {
                backgroundWorker.RunWorkerAsync();
            }
            
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (toolStripProgressBarConnecting.Value < toolStripProgressBarConnecting.Maximum)
                toolStripProgressBarConnecting.Increment(5);
            else
                toolStripProgressBarConnecting.Value = toolStripProgressBarConnecting.Minimum;
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    testConnection();

                    System.Threading.Thread.Sleep(10);
                    worker.ReportProgress((i * 10));
                }
            }            
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                //this.tbProgress.Text = "Canceled!";
            }
            else if (!(e.Error == null))
            {
                this.Invoke(new Action(() => { showErrroBox(e.Error.Message + "\n" + this.connError); }));
            }
            else
            {
                this.labelServer.Visible = true;
                this.labelIamConn.Visible = true;
            }


            this.textBoxConnectionString.Enabled = true;
            this.buttonTest.Enabled = true;
            this.toolStripProgressBarConnecting.Visible = false;

            if(!this.connError.Equals(""))
                this.Invoke(new Action(() => { showErrroBox(this.connError); })); 

        }

        private void labelServer_MouseHover(object sender, EventArgs e)
        {
            toolTipServer.SetToolTip(this.labelServer, this.labelServer.Text);
        }

        private void showErrroBox(string message) {
            MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void moreAboutConnectionStringToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://msdn.microsoft.com/library/ms254500(v=vs.100).aspx");
        }

        private void reToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        /*
            Implements the CTRL+A (select all) shrtcut wich is not supportedon multiline TexBox
        */
        private void textBoxConnectionString_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && (e.KeyCode == Keys.A))
            {
                if (sender != null)
                    ((TextBox)sender).SelectAll();
                e.Handled = true;
            }
        }

        /*
            Save TextBox values
        */
        private void toolStripMenuItemSave_Click(object sender, EventArgs e)
        {
            // Update the value.
            Properties.Settings.Default.ConnString = this.textBoxConnectionString.Text;
            Properties.Settings.Default.Save();
        }

        private void moreAboutConnectionStringToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://msdn.microsoft.com/library/ms254500(v=vs.100).aspx");
        }

        private void reportABugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("mailto:murilo.miranda@doctordata.pt?subject=[BUG] Where am I connected");
        }
    }
}
